package projectmanagement.web;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.validation.BindException;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.SimpleFormController;

import projectmanagement.model.Person;
import projectmanagement.model.Project;
import projectmanagement.model.dao.PersonDao;
import projectmanagement.model.dao.ProjectDao;

public class EnterProjectController extends SimpleFormController {
	public static final String PROJECT_ID = "id";
	public static final String ACTION = "action";
	public static final String ACTION_NEW = "new";
	public static final String ACTION_EDIT = "edit";

	private ProjectDao projectManager;
	private PersonDao personManager;

	protected Object formBackingObject(HttpServletRequest request)
			throws Exception {

		String id = request.getParameter(PROJECT_ID);
		String action = request.getParameter(ACTION);

		if (action != null && action.length() > 0) {
			if (action.equals(ACTION_EDIT) && id != null
					&& id.trim().length() > 0) {
				Project project = this.projectManager.getProjectById(Integer
						.parseInt(id));
				return project;
			} else if (action.equals(ACTION_NEW) && id == null) {
				return new Project();
			} else {
				throw new Exception();
			}
		}

		return null;
	}

	public void onBindAndValidate(HttpServletRequest request, Object command,
			BindException errors) throws Exception {
		if (errors.hasErrors())
			return;

		Project project = (Project) command;
		String action = request.getParameter(ACTION);

		if (action != null && action.length() > 0
				&& (action.equals(ACTION_NEW) || action.equals(ACTION_EDIT))) {
			projectManager.save(project);
		} else {
			throw new Exception();
		}
	}

	protected Map<String, Map<String, String>> referenceData(
			HttpServletRequest request) throws Exception {
		HashMap<String, String> persons = new HashMap<String, String>();

		List<Person> personList = personManager.getPersonList();
		for (int i = 0; i < personList.size(); i++) {
			persons.put(String.valueOf(personList.get(i).getId()), personList
					.get(i).getName()
					+ " " + personList.get(i).getSurname());
		}

		HashMap<String, Map<String, String>> model = new HashMap<String, Map<String, String>>();
		model.put("personList", persons);

		return model;
	}

	public ModelAndView onSubmit(HttpServletRequest request,
			HttpServletResponse response, Object command, BindException errors)
			throws Exception {
		return new ModelAndView(getSuccessView());
	}

	public ProjectDao getProjectManager() {
		return projectManager;
	}

	public void setProjectManager(ProjectDao projectManager) {
		this.projectManager = projectManager;
	}

	public PersonDao getPersonManager() {
		return personManager;
	}

	public void setPersonManager(PersonDao personManager) {
		this.personManager = personManager;
	}
}
